package cn.czxy.web.servlet.flie;

import cn.czxy.config.FileService;
import cn.czxy.domain.AllFile;
import cn.czxy.domain.User;
import cn.czxy.service.file.FileServiceImpl;
import cn.czxy.utils.FileDataUtils2;
import cn.czxy.utils.FileTypeUtlis;
import cn.itcast.servlet.BaseServlet;
import org.apache.commons.io.FileUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨先生
 * @version 1.0
 * @date 2019/4/12
 */
public class FileServlet extends BaseServlet {

    /** service层的对象 */
    private FileService service = new FileServiceImpl();
    /** 项目的用户对应的路径信息 */
    private String userPath;
    /** 定于展示个数 */
    private Integer pageSize = 20;

    /** 记录上一次传入的文件地址 */
    private String path;
    /** 记录编码后地址值 */
    private String decode;
    /** 记录上次查询的list文件集合 */
    private List<AllFile> list;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        userPath = config.getServletContext().getRealPath("/files");
    }






    /**
     * 获取字符的编码格式
     * @param str
     * @return
     */
    public  String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }



    /**
     * 文件上传解析
     * @return
     */
    public String upLoad() throws ServletException, IOException {

        FileDataUtils2 fileutils = new FileDataUtils2(userPath + "\\");
        User user = (User)getSession().getAttribute("user");
        boolean b = fileutils.addFile(user.getUserName(), getRequest(), getResponse());
        String address = null;
        if (b){
            address = "文件上传成功";
        }else{
            address = "文件格式错误上传失败";


//            getRequest().getRequestDispatcher("/demand/main.jsp").forward(null,getResponse());
            return null;
        }
        getRequest().setAttribute("address",address);
        return "forward:/file?method=findFlieByPath&path=/";
    }




    /**
     * 查询文件夹
     * @return
     * @throws UnsupportedEncodingException
     */
    public String findFlieByPath() throws UnsupportedEncodingException {

        User user = (User)getSession().getAttribute("user");
        String userPath = null;
        if (user != null){
            userPath = this.userPath+"/"+user.getUserName();
        }else{
            userPath = this.userPath+"/user1";
        }


        if (getRequest().getParameter("currentPage") == null){
            path = getRequest().getParameter("path");
            decode = URLDecoder.decode(path, "utf-8");
            userPath = userPath+decode;
            list = service.findFlieByPath(userPath);
        }



        if (list == null || list.size() == 0){
            getRequest().setAttribute("msg","文件夹空空如也");
        }else{
            page(list);
        }
        return "forward:/demand/main.jsp";
    }


    /**
     * 用于分页展示
     * @param flieByPath
     */
    public void page(List<AllFile> flieByPath ){
        //设定展示第一页
        Integer currentPage = 1;  //第一页
        HttpServletRequest request = getRequest();
        //获取当前的页数
        String curPage = request.getParameter("currentPage");
        if (curPage != null && !"".equals(curPage)) {
            //给当前页数赋值
            currentPage = Integer.parseInt(curPage);
        }
        //list集合中存储每页需要展示
        ArrayList<AllFile> showData = new ArrayList<>();
        //往list集合中填充需要展示的
        for (int i = 0; i < pageSize; i++) {
            //根据当前页数计算出需要展示的数据
            if (((currentPage - 1) * pageSize + i) < flieByPath.size()) {
                showData.add(flieByPath.get((currentPage - 1) * pageSize + i));
            }
        }
        //展示显示数据
        request.setAttribute("flieList", showData);
        //当前的页面页码展示
        request.setAttribute("currentPage", currentPage);
        //用来判断页数的多少的  不够整除的话页数需要另外在展示一页
        Integer totalPage = flieByPath.size() % pageSize == 0 ? flieByPath.size() / pageSize : flieByPath.size() / pageSize + 1;
        request.setAttribute("totalPage", totalPage);
        //固定的值每一个页面展示多少行代码
        request.setAttribute("pageSize", pageSize);
    }





    /**
     * 展示文本
     * 展示页面的文件
     * @return
     */
    public String showFile() throws IOException {
        String fileName = getRequest().getParameter("fileName");
        String id = getRequest().getParameter("id");
        //判断文件类型如果是 文件夹就直接调用 查询方法并返回到 main.jsp
        if (id != null && id.equals("0")){
            List<AllFile> list = service.findFlieByPath(getServletContext().getRealPath(fileName));
            page(list);
            return "forward:/demand/main.jsp";
        }
        //处理中文乱码 tomcat 8 不用处理中文乱码
        //fileName = new String(fileName.getBytes("iso8859-1"),"utf-8");
        fileName = URLDecoder.decode(fileName,"utf-8");

        //获取到文件的 type 属性
        //删除无用属性 使用工具类获取
       id = FileTypeUtlis.getFileType(fileName);

        //获取到文件的 后缀名
        String typeName = fileName.substring(fileName.lastIndexOf(".") + 1);



        //判断如果是text类型的文件
        if (id.equals("1")){
            String realPath = getServletContext().getRealPath("/");
            File file = new File(realPath+fileName);

            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String encoding = getEncoding(bufferedReader.readLine());
            System.out.println(encoding);
            List<String> tlist = FileUtils.readLines(file, encoding);
            ArrayList<String> list = new ArrayList<>();
            list.add("一");list.add("二");list.add("三");list.add("四");list.add("五");list.add("六");list.add("七");list.add("八");list.add("九");list.add("十");
            for (int i = 0; i < tlist.size(); i++) {
                String s = tlist.get(i);
                if (i==0){
                    String str="<h1 align='center'>"+s+"</h1>";
                    tlist.set(i,str);
                }
                if (s.length()>0){
                    String substring = s.substring(0, 1);
                    if (list.contains(substring)){
                        String str="<h1>"+s+"</h1>";
                        tlist.set(i,str);
                    }
                }
            }
            getRequest().setAttribute("tlist", tlist);
            fileReader.close();
        }

        //保存所有的 数据类型到 request中
        getRequest().setAttribute("fileName",fileName);
        getRequest().setAttribute("type",id);
        getRequest().setAttribute("typeName",typeName);

        if (getRequest().getParameter("flag") == null){
            return "forward:/demand/show.jsp";
        }else {
            return "forward:/demand/shareShow.jsp";
        }
    }


    /**
     * 文件下载
     * @return
     * @throws UnsupportedEncodingException
     */
    public String downLoad() throws UnsupportedEncodingException {
        String fileName = getRequest().getParameter("fileName");
        fileName = URLDecoder.decode(fileName,"utf-8");
        String realPath = getServletContext().getRealPath(fileName);
        FileDataUtils2 fileData = new FileDataUtils2(getServletContext().getRealPath("/files\\"));
        fileData.downLoadFile(realPath,getRequest(),getResponse());

        return "forward:/file?method=findFlieByPath&path=/";
    }



    /**
     * 查询
     * @return
     * 获取文件名
     */
    public String search(){
        //输出的数据
        List<AllFile> list = new ArrayList<>();

        String fileName = getRequest().getParameter("search");

        if (fileName==null||fileName.length()==0)
        {
            return "redirect:/demand/top.jsp";
        }

        User user = (User) getRequest().getSession().getAttribute("user");

        if (user==null||user.getUserName()==null||user.getUserName().length()==0)
        {
            return "redirect:/demand/top.jsp";
        }
        //!!! 这里的路劲是绝对路径
        String path =userPath+"\\";
        path = path +"\\"+user.getUserName();

        File file1 = new File(path + "\\" + "imges");
        File file2 = new File(path + "\\" + "music");
        File file3 = new File(path + "\\" + "other");
        File file4 = new File(path + "\\" + "texts");
        File file5 = new File(path + "\\" + "videos");

        ArrayList<File> typeList = new ArrayList<>();
        typeList.add(file1);
        typeList.add(file2);
        typeList.add(file3);
        typeList.add(file4);
        typeList.add(file5);


        for (File f : typeList) {
            for (File file : f.listFiles()) {
                if (file.getName().contains(fileName))
                {
                    String absolutePath = file.getAbsolutePath();
                    AllFile allFile = new AllFile();
                    allFile.setName(file.getName());
                    allFile.setRealPath(absolutePath);

                    String fileNames = FileTypeUtlis.getFileName(absolutePath);
                    String encode = null;
                    try {

                        encode = URLEncoder.encode(fileNames, "utf-8");
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
//                前段工具类提供信息
                    allFile.setFileName(encode);
                    allFile.setType(FileTypeUtlis.getFileType(absolutePath));
                    list.add(allFile);
                }
            }
        }

        page(list);
        for (AllFile allFile : list) {
            System.out.println(allFile);
        }

        return "forward:/demand/main.jsp";
    }
}
